package com.mingqi.enetconnected.base;

import android.app.Application;
import android.content.Context;
import android.os.Environment;
import android.support.multidex.MultiDex;
import android.text.TextUtils;

import com.facebook.stetho.Stetho;
import com.facebook.stetho.okhttp3.StethoInterceptor;
import com.lzy.okgo.OkGo;
import com.mingqi.enetconnected.R;
import com.mingqi.enetconnected.location.service.LocationService;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.api.UIKitOptions;
import com.netease.nim.uikit.business.contact.core.query.PinYin;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.mixpush.NIMPushClient;
import com.netease.nimlib.sdk.util.NIMUtil;
import com.mingqi.enetconnected.three.im.DemoCache;
import com.mingqi.enetconnected.three.im.NIMInitManager;
import com.mingqi.enetconnected.three.im.NimSDKOptionConfig;
import com.mingqi.enetconnected.three.im.config.preference.Preferences;
import com.mingqi.enetconnected.three.im.config.preference.UserPreferences;
import com.mingqi.enetconnected.three.im.contact.ContactHelper;
import com.mingqi.enetconnected.three.im.event.DemoOnlineStateContentProvider;
import com.mingqi.enetconnected.three.im.mixpush.DemoMixPushMessageHandler;
import com.mingqi.enetconnected.three.im.mixpush.DemoPushContentProvider;
import com.mingqi.enetconnected.three.im.session.SessionHelper;
import com.mingqi.enetconnected.util.crash.CrashHandler;
import com.mingqi.enetconnected.util.log.Log2FileUtils;
import com.mingqi.enetconnected.util.log.LogUtils;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

import java.io.File;

import okhttp3.OkHttpClient;

/**
 * Created by li on 2018/7/30.
 * WeChat 18571658038
 * author LiWei
 */

public class MyApplication extends Application {
    public final static boolean isDebug = true;
    public final static String PACKAGE_NAME = "com.mingqi.enetconnected";
    public static Context sContext;
    public LocationService locationService;

    public static String folder = "towngasCS";
    public static String projDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + folder;
    public final static String VERSION_PATH = projDir + "/version";
    public final static String PIC_PATH = projDir + "/photo";
    public final static String DOWNLOAD_PATH = projDir + "/download";

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(newBase);
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();

        sContext = this;
        initApplicationEnv();
        locationService = new LocationService(getApplicationContext());

        //配置chrome调试
        initStetho();
        //初始化OkGo，含OKHttp的Stetho调试拦截器
        initOkGo();
        //内存泄漏检测
        initLeakCanary();

        //初始化日志写入文件工具
        initLog2File();

        // debug模式
        LogUtils.controlDebug(true);
        LogUtils.TAG = "--TAG--";

        ZXingLibrary.initDisplayOpinion(this);

        // 捕获异常
//        CrashHandler crashHandler = CrashHandler.getInstance();
//        crashHandler.init(this);

        DemoCache.setContext(this);
        // 4.6.0 开始，第三方推送配置入口改为 SDKOption#mixPushConfig，旧版配置方式依旧支持。
        NIMClient.init(this, getLoginInfo(), NimSDKOptionConfig.getSDKOptions(this));

        // 以下逻辑只在主进程初始化时执行
        if (NIMUtil.isMainProcess(this)) {

            // 注册自定义推送消息处理，这个是可选项
            NIMPushClient.registerMixPushMessageHandler(new DemoMixPushMessageHandler());

            // init pinyin
            PinYin.init(this);
            PinYin.validate();
            // 初始化UIKit模块
            initUIKit();
            // 初始化消息提醒
            NIMClient.toggleNotification(UserPreferences.getNotificationToggle());
            // 云信sdk相关业务初始化
            NIMInitManager.getInstance().init(true);
        }
    }

    private void initLog2File() {

        Log2FileUtils.init(this);
    }

    private void initOkGo() {

        //注意:下面这段话是为OkHttpClient配置拦截器,只有用这个OkHttpClient请求数据才能被拦截
        OkHttpClient client = new OkHttpClient.Builder()
                //添加Stetho的拦截器
                .addNetworkInterceptor(new StethoInterceptor())
                .build();

        //初始化OkGo
        OkGo.getInstance().init(this)
                .setOkHttpClient(client);
    }

    private void initStetho() {

        Stetho.initialize(
                Stetho.newInitializerBuilder(this)
                        .enableDumpapp(Stetho.defaultDumperPluginsProvider(this))
                        .enableWebKitInspector(Stetho.defaultInspectorModulesProvider(this))
                        .build());
    }

    private void initLeakCanary() {

//        if (LeakCanary.isInAnalyzerProcess(this)) {
//            return;
//        } else {
//
//            LeakCanary.install(this);
//        }
    }

    private LoginInfo getLoginInfo() {
        String account = Preferences.getUserAccount();
        String token = Preferences.getUserToken();

        if (!TextUtils.isEmpty(account) && !TextUtils.isEmpty(token)) {
            DemoCache.setAccount(account.toLowerCase());
            return new LoginInfo(account, token);
        } else {
            return null;
        }
    }

    private void initUIKit() {
        // 初始化
        NimUIKit.init(this, buildUIKitOptions());

        // IM 会话窗口的定制初始化。
        SessionHelper.init();

        // 通讯录列表定制初始化
        ContactHelper.init();

        // 添加自定义推送文案以及选项，请开发者在各端（Android、IOS、PC、Web）消息发送时保持一致，以免出现通知不一致的情况
        NimUIKit.setCustomPushContentProvider(new DemoPushContentProvider());

        NimUIKit.setOnlineStateContentProvider(new DemoOnlineStateContentProvider());
    }

    private UIKitOptions buildUIKitOptions() {
        UIKitOptions options = new UIKitOptions();
        // 设置app图片/音频/日志等缓存目录
        options.appCacheDir = NimSDKOptionConfig.getAppCacheDir(this) + "/app";
        return options;
    }

    public static int getSysIcon() {
        return R.drawable.ic_launcher_background;
    }

    private void initApplicationEnv() {

        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            File projectDir = new File(projDir + "/Log");
            projectDir.mkdirs();

            projectDir = new File(projDir + "/icon");
            projectDir.mkdirs();

            projectDir = new File(projDir + "/BillData");
            projectDir.mkdirs();

            projectDir = new File(projDir + "/icon/size_m");
            projectDir.mkdirs();

            projectDir = new File(projDir + "/version");
            projectDir.mkdirs();

            projectDir = new File(projDir + "/download");
            projectDir.mkdirs();
            projectDir = new File(projDir + "/photo");
            projectDir.mkdirs();
        }
    }
}
